package com.io.nettyflow.rounter;

import com.io.model.RegisterReq;
import com.io.model.TerminalPrincipal;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by yangyx on 2016/8/1.
 */
@Component
public class ContextManager {

    static final Logger logger= LoggerFactory.getLogger(ContextManager.class);
    //当前存在的channelId;key:tid,value:channelId(只是名字)
    private ConcurrentHashMap<String, String> tid2ChannelId = new ConcurrentHashMap<String, String>();
    //key:channelId,value:存在的实体
    private ConcurrentHashMap<String, RegisterReq> channelId2RegisterReq = new ConcurrentHashMap<String, RegisterReq>();
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/1 16:11
     *查看输出数据使用
     */
    public void printDebug() {
        logger.debug(">>>>>>>>>>>>>>>>");
        for(String channelId : channelId2RegisterReq.keySet()) {
            logger.debug(channelId + " => " + channelId2RegisterReq.get(channelId).getTerminalID());
        }
        logger.debug("----------------");

        for(String tid : tid2ChannelId.keySet()){
            logger.debug(tid + " => " + tid2ChannelId.get(tid));
        }
        logger.debug("<<<<<<<<<<<<<<<<");
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/2 9:45
     *清除该链接的现有通道
     */
    public void removePrincipalOfContext(ChannelHandlerContext ctx) {
        String channelId = ctx.channel().id().asLongText();
        RegisterReq principal = channelId2RegisterReq.getOrDefault(channelId, null);
        if(principal!=null){
            if(channelId.equals(tid2ChannelId.getOrDefault(principal.getTerminalID(), null))){
                tid2ChannelId.remove(principal.getTerminalID());
            }
            channelId2RegisterReq.remove(channelId);
        }
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/2 10:41
     *用户身份确认时候调用
     */
    public void setRegisterReq(RegisterReq obj) {
        String tid=obj.getTerminalID();
        String channelId=obj.getCtx().channel().id().asLongText();
        tid2ChannelId.put(tid,channelId);
        channelId2RegisterReq.put(channelId,obj);
        logger.info("===向tid2ChannelId内存入key"+tid+", value="+channelId);
        logger.info("===向channelId2RegisterReq内存入key"+channelId+", value="+obj);
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/2 10:50
     *根据id查看该用户终端是否已经登录，
     * 返回null说明还没有登录，返回实体代表已经登录
     */
    public RegisterReq getPrincipalByTid(String tid) {
        String channelId=tid2ChannelId.getOrDefault(tid,null);
        if(channelId!=null){
            return channelId2RegisterReq.getOrDefault(channelId,null);
        }
        return null;
    }
}
